package com.movie.repository;

import com.movie.entity.News;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 资讯数据访问接口
 */
@Repository
public interface NewsRepository extends JpaRepository<News, Long> {
    
    /**
     * 根据分类查找已发布的资讯
     */
    @Query("SELECT n FROM News n WHERE n.category.name = :categoryName AND n.isPublished = true")
    Page<News> findByCategoryNameAndIsPublishedTrue(@Param("categoryName") String categoryName, Pageable pageable);
    
    /**
     * 查找所有已发布的资讯
     */
    Page<News> findByIsPublishedTrue(Pageable pageable);
    
    /**
     * 查找置顶的资讯
     */
    List<News> findByIsTopTrueAndIsPublishedTrueOrderByPublishTimeDesc();
    
    /**
     * 根据标题搜索资讯
     */
    @Query("SELECT n FROM News n WHERE n.title LIKE %:keyword% AND n.isPublished = true")
    Page<News> searchByTitle(@Param("keyword") String keyword, Pageable pageable);
    
    /**
     * 查找热门资讯（按浏览量排序）
     */
    Page<News> findByIsPublishedTrueOrderByViewCountDesc(Pageable pageable);
    
    /**
     * 查找最新资讯
     */
    Page<News> findByIsPublishedTrueOrderByPublishTimeDesc(Pageable pageable);
    
    /**
     * 根据分类、发布状态、置顶状态查找资讯
     */
    @Query("SELECT n FROM News n WHERE n.category.name = :categoryName AND n.isPublished = :isPublished AND n.isTop = :isTop")
    Page<News> findByCategoryNameAndIsPublishedAndIsTop(@Param("categoryName") String categoryName, @Param("isPublished") Boolean isPublished, @Param("isTop") Boolean isTop, Pageable pageable);
    
    /**
     * 根据分类和发布状态查找资讯
     */
    @Query("SELECT n FROM News n WHERE n.category.name = :categoryName AND n.isPublished = :isPublished")
    Page<News> findByCategoryNameAndIsPublished(@Param("categoryName") String categoryName, @Param("isPublished") Boolean isPublished, Pageable pageable);
    
    /**
     * 根据分类和置顶状态查找资讯
     */
    @Query("SELECT n FROM News n WHERE n.category.name = :categoryName AND n.isTop = :isTop")
    Page<News> findByCategoryNameAndIsTop(@Param("categoryName") String categoryName, @Param("isTop") Boolean isTop, Pageable pageable);
    
    /**
     * 根据分类查找资讯
     */
    @Query("SELECT n FROM News n WHERE n.category.name = :categoryName")
    Page<News> findByCategoryName(@Param("categoryName") String categoryName, Pageable pageable);
    
    /**
     * 根据发布状态和置顶状态查找资讯
     */
    Page<News> findByIsPublishedAndIsTop(Boolean isPublished, Boolean isTop, Pageable pageable);
    
    /**
     * 根据发布状态查找资讯
     */
    Page<News> findByIsPublished(Boolean isPublished, Pageable pageable);
    
    /**
     * 根据置顶状态查找资讯
     */
    Page<News> findByIsTop(Boolean isTop, Pageable pageable);
}